package com.atzxh.guigu.juc.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemo1 {
    public static void main(String[] args) {
        Share share = new Share();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.add();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"aa").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.sub();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"bb").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.add();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"cc").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.sub();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"dd").start();
    }
}
class Share {
    private int num = 0;

    // 创建Lock对象
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    // 加一
    public void add() throws InterruptedException {
        // 上锁
        lock.lock();
        try {
            // 判断
            while (num != 0) {
                condition.await();
            }
            // 干活
            num++;
            System.out.println(Thread.currentThread().getName() + " :: " + num);
            // 通知
            condition.signalAll();
        } finally {
            // 解锁
            lock.unlock();
        }
    }

    // 减一
    public void sub() throws InterruptedException {
        // 上锁
        lock.lock();
        try {
            // 判断
            while (num != 1) {
                condition.wait();
            }
            // 干活
            num--;
            System.out.println(Thread.currentThread().getName() + " :: " + num);
            // 通知
            condition.signalAll();
        } finally {
            // 解锁
            lock.unlock();
        }
    }
}